
// 文件上传  微信端使用微信自带， 否则使用默认开的
;(function(window , $,undefined){
  var uuid = 0;
  // 判断客户端是不是微信 以及 是不是本地
  var isLocal = function () {
    var hostname = window.location.hostname;
    var regx = /(localhost)|(127\.0\.0\.1)|(192\.168\.)/ig;
    return regx.test(hostname);
  }();

  var isWeChat = function () {
    var ua = window.navigator.userAgent;
    var regx = /MicroMessenger/ig;
    return regx.test(ua);
  }();


  /** 用户创建弹窗 */

  function inherit(parent , child){
    function temp(){}
    temp.prototype = parent.prototype ;
    child.prototype = new temp ;
    child.prototype.constructor = child;
  }


  function ParentElement(params){this.params = params || {};}

  ParentElement.prototype.createElement = function(tag , className , children){
    var elem = document.createElement(tag);
    elem.setAttribute('class',className);
    if(children && children.length){
      children.forEach(function(child) {
        elem.appendChild(child);
      })
    }
    return elem;
  }

  // 创建通用节点
  ParentElement.prototype.createCommonNode = function(elem){
    var btnOkText = document.createTextNode('确定');
    var btnRestText = document.createTextNode('重新选择');
    this.btnOk = this.createElement('div','cropper-popup-btn-ok',[btnOkText]);
    this.btnReset = this.createElement('div','cropper-popup-btn-reset',[btnRestText]);
    var btnGroup = this.createElement('div','cropper-popup-btn-group',[this.btnReset , this.btnOk]);
    this.popup = this.createElement('div','cropper-popup',[ elem , btnGroup]);

  }
  ParentElement.prototype.bineOne = function(elem , eventNames, fn){
    var self = this;
    var tempFn = function(){
      tempFn.fn.apply(self,arguments);
      self.unbind(self.popup , eventNames,tempFn);
    }
    tempFn.fn = fn;
    if(eventNames && typeof eventNames !== "string" && eventNames.length){
      eventNames.forEach(function(eventName){
        elem.addEventListener(eventName , tempFn, false);
      })
    }else {
      elem.addEventListener(eventName , tempFn, false);
    }

  }
  ParentElement.prototype.unbind = function(elem, eventNames , fn){
    if(eventNames && typeof eventNames !== "string" && eventNames.length){
      eventNames.forEach(function(eventName){
        elem.removeEventListener(eventName , fn ,false);
      })
    }else {
      elem.removeEventListener(eventNames , fn ,false);
    }
  }
  // 显示节点
  ParentElement.prototype.show = function(elem){
    var self = this;
    this.createCommonNode(elem);
    document.body.appendChild(this.popup);

    this.btnOk.addEventListener('click',function(){
      self.hide(self.params.onOk);
    },false);
    this.btnReset.addEventListener('click',function(){
      self.hide(self.params.onReset);
    })
    this.bineOne(this.popup,['webkitTransitionEnd','transitionend'],function(){
      this.popup.classList.remove('fade-enter-to','fade-enter-active');
    });
    this.popup.classList.add('fade-enter');

    var self = this;
    setTimeout(function(){
      self.popup.classList.remove('fade-enter');
      self.popup.classList.add('fade-enter-to' ,'fade-enter-active');
    },1000 / 60);
  }
  // 隐藏节点
  ParentElement.prototype.hide = function(callback){
    this.bineOne(this.popup,['webkitTransitionEnd','transitionend'],function(){
      this.popup.classList.remove('fade-leave-to','fade-leave-active');
      this.popup.parentNode && this.popup.parentNode.removeChild(this.popup);
      callback && callback.apply(self);
    });
    this.popup.classList.add('fade-leave');
    var self = this;
    setTimeout(function(){
      self.popup.classList.remove('fade-leave');
      self.popup.classList.add('fade-leave-to' ,'fade-leave-active');
    },1000 / 60)
  }




  function CommonUpload(elem,options){
    this.options = options || {};
    this.maxWidth = this.options.maxWidth || 1024;
    this.$elem = $(elem);
    this.uuid = ++uuid;
    this.width = this.options.width ? this.options.width : this.$elem.width();
    this.height = this.options.height ? this.options.height : this.$elem.height();
    this.cropper = null;
    var self = this;
    this.cropperPopup =  new ParentElement({
      onOk:this.onOk.bind(this),
      onReset:this.onRechoose.bind(this)
    });
    if(isLocal || !isWeChat){ // 如果是本地 ，或者不是微信端
      this.UploadFileKey = 'uploadFile'+ this.uuid ;
      this.$elem.data('id',this.UploadFileKey);
      this.upload = new UploadFile({
        uploadId:this.UploadFileKey,
        maxWidth:this.maxWidth
      });

      this.label = $("<label></label>",{
        'class': "upload-file-label upload-file-label"+this.uuid,
        'for' : this.UploadFileKey
      });
      this.$elem.append(this.label);
      this.$elem.$uploadObject = this.upload;
      this.upload.on('loadstart',this.onUploadStart.bind(this));
      this.upload.on('loadprogress',this.onUploadProgress.bind(this));
      this.upload.on('loadfinish',this.onUploadFinish.bind(this));
    }else {
      this.$elem.on('click',this.chooseImage.bind(this))
    }


  }

  CommonUpload.prototype.chooseImage = function(){
    var self = this;
    wx.chooseImage({
      count:1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res){
        var localIds = res.localIds;
        self.onUploadStart();
        self.getLocalImgData(localIds[0]);
      }
    })
  }

  CommonUpload.prototype.getLocalImgData = function(localId){
    var self = this;
    wx.getLocalImgData({
      localId: localId,
      success: function (res) {
        var localData = res.localData;
        if (localData.indexOf('data:image') !== 0) {
            localData = 'data:image/jpeg;base64,' +  localData;
        }
        localData = localData.replace(/\r|\n/g, '').replace('data:image/jgp', 'data:image/jpeg');
        self.onUploadFinish({result:localData});
      }
    });
  }
  CommonUpload.prototype.onUploadStart = function(){
    this.$elem.trigger('loadStart');
  }
  CommonUpload.prototype.onUploadProgress = function(){
    this.$elem.trigger('loadProgress');
  }
  CommonUpload.prototype.onUploadFinish = function(res){
    var self = this;
    this.$elem.trigger('loadComplete',res.result);
    this.compress(res.result,function (canvas) {
      self.createCropper(canvas)
    });
  }

  CommonUpload.prototype.compress = function(url , callback){
    var self = this;
    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var img = new Image();
    img.onload = function () {
      var per = this.height / this.width;
      canvas.width = this.width > self.maxWidth ? self.maxWidth : img.width;
      canvas.height = canvas.width * per;
      ctx.drawImage(this, 0, 0, img.width, img.height, 0, 0, canvas.width, canvas.height);
      callback && callback(canvas);
    };
    img.src = url;
  }


  CommonUpload.prototype.createCropper = function(canvas){
    this.cropperPopup.show(canvas);
    console.log('createCropper', this.width, this.height)
    this.cropper = new Cropper(canvas, {
      aspectRatio: this.width / this.height,
      viewMode: 1,
      autoCropArea:0.8,
      dragMode:'move',
      guides:true,
      minCropBoxWidth: 200,
      cropBoxResizable:true,
      cropBoxMovable:true
    });

  }
  CommonUpload.prototype.onRechoose = function(){
    this.upload.oInput.value = '';
    this.cropper && this.cropper.destroy();
  }
  CommonUpload.prototype.onOk = function(){
    var uf = this.upload ,  imageType = uf && uf.file ? uf.file.type :'image/jpeg';
    if(this.cropper){
      var canvas = this.cropper.getCroppedCanvas();
      var base64 = canvas.toDataURL(imageType,1) ;

      var blob = this.dataURLtoBlob(base64);
      var fileName = this.getFileName(base64);
      var fileType = this.getFileType(base64);
      var fileObject = this.blobToFile(blob , fileName);
      this.$elem.trigger('cropComplete',{
        fileName: fileName ,
        fileType: fileType,
        blob:blob,
        file:fileObject,
        url: window.URL.createObjectURL(blob),
        base64: base64
      });
    }
  }
  CommonUpload.prototype.getFileName = function(base64){
    var name = Math.random().toString(36).substr(2) + (+new Date());
    return name +  '.' +this.getFileType(base64);
  }
  CommonUpload.prototype.getFileType =  function(name){
      var match = name.match(/data:image\/(.*);/i);
      return match[1] ? match[1] : 'jpg';
  }
  CommonUpload.prototype.blobToFile = function(theBlob, fileName){
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
  }
  CommonUpload.prototype.dataURLtoBlob = function(dataurl){
    var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }


  $.fn.upload = function(options){
    options = options || {};
    return this.each(function(index,elem){
      new CommonUpload(elem , options);
    })
  }




})(window,Zepto || JQuery);



;(function(){
  var href = location.href,
    eventDomain = href.substr(0, href.lastIndexOf('/') + 1);

  function TencetCloudUploadFile(params){
    this.params = params = params || {};
    var self = this;
    this.path = params.path || '';
    this.Bucket = params.Bucket || 'yinduogilvy-1251454229';
    this.Region = params.Region || 'ap-shanghai';
    this.authUrl =  params.authUrl || eventDomain + 'sign.php' ;
    var hm = document.createElement("script");
    var s = document.getElementsByTagName("script")[0];
    hm.type = 'text/javascript';
    s.parentNode.insertBefore(hm, s);
    hm.onload = s.onreadystatechange = function(){
      if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){
        self.initCos()
      }
    } //
    hm.src = "https://yinduogilvy-1251454229.file.myqcloud.com/common/v1/cos-js-sdk-v5.min.js";
  }
  TencetCloudUploadFile.prototype.initCos = function(){
    var self = this;
    var cos = this.cos = new COS({
      getAuthorization: function (options, callback) {
        // 异步获取临时密钥
        $.get(self.authUrl, {
          bucket: options.Bucket,
          region: options.Region,
        }, function (data) {
          var credentials = data && data.credentials;
          if (!data || !credentials) return console.error('credentials invalid');
          callback({
            TmpSecretId: credentials.tmpSecretId,
            TmpSecretKey: credentials.tmpSecretKey,
            XCosSecurityToken: credentials.sessionToken,
            // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
            StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
            ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
          });
        });
      },
    });
  }
  TencetCloudUploadFile.prototype.putObject = function(file,callback){

    this.cos.putObject({
      Bucket: this.Bucket,
      Region: this.Region,
      Key: this.path + file.name,
      Body: file,
    }, callback);
  }
  window.TencetCloudUploadFile = TencetCloudUploadFile;
})();

